﻿using System;
using RuTracker.Interface;
using RuTracker.Interface.Editors;
using RuTracker.Interface.Login;
using RuTrackerLib.Editors;

namespace RuTrackerLib.Tracker.RequestProcessors
{
    class LinkRequestProcessor : IRequestProcessor
    {
        private readonly IResponseLexer _lexer;
        private readonly ITrackerAccessor _trackerAccessor;
        private readonly IUserRepository _userRepository;
        private readonly ISessionStorage _sessionStorage;
        private readonly IHtmlEditor[] _editors;

        public LinkRequestProcessor(IResponseLexer lexer
            , ITrackerAccessor trackerAccessor
            , IUserRepository userRepository
            , ISessionStorage sessionStorage
            , IHtmlEditor[] editors)
        {
            _editors = editors;
            _sessionStorage = sessionStorage;
            _lexer = lexer;
            _trackerAccessor = trackerAccessor;
            _userRepository = userRepository;
        }

        public RequestProcessingResults ProcessRequest(string query, string user)
        {
            string url = query;
            if (string.IsNullOrWhiteSpace(url))
                url = _trackerAccessor.TrackerInfo.DefaultUrl;            

            try
            {
                _sessionStorage.CurrentFolder = WebFolderManager.GetParentFolder(url);
            }
            catch (Exception) { }

            return ProcessUrl(url, user);
        }

        private RequestProcessingResults ProcessUrl(string url, string userName, bool isReloginAttempt = false)
        {
            HtmlEditor editor = new HtmlEditor(_editors);
            User user = _userRepository.GetUser(userName);
            LoginResults loginResults = _trackerAccessor.GoToAddress(url);

            bool isReloginRequired = !loginResults.Succeeded;

            RequestProcessingResults result = new RequestProcessingResults
            {
                IsLoginRequired = isReloginRequired,
                IsTorrentAvailable = _lexer.ContainsTorrent(loginResults.Html)
            };

            if (isReloginRequired && !isReloginAttempt)
            {
                var loginResult = _trackerAccessor.SignIn(user.Name, user.Password);
                if (loginResult.Succeeded)
                    return ProcessUrl(url, userName, true);
            }

            if (!isReloginRequired)
                result.Html = string.Format("<html>{0}</html>", editor.Edit(loginResults.Html));

            return result;
        }
    }
}
